package com.jinlejia.erp.ui.mine.transfer;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.TransferBean;
import com.jinlejia.erp.databinding.ActivityTransferApplyTypeBinding;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;


/**
 * 异动申请-选择异动类型
 */
public class TransferApplyTypeActivity extends AppCompatActivity {
    TransferBean transferBean = new TransferBean();
    private Boolean lower;
    private String userLevel;
    private ArrayList<Map<String,Object>> reasonsForChangeList;//异动原因集合
    private ArrayList<Map<String,Object>> recruitmentChannelsList;//招募渠道集合
    private String typeCode;
    private ActivityTransferApplyTypeBinding binding;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_transfer_apply_type);
        binding.setEvent(this);
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        progressDialog = new ProgressDialog(this, "加载中...");
        progressDialog.setCancelable(false);
        formatStr(binding.tvType, "*");
        formatStr(binding.tvReasons, "*");
    }

    private Intent mIntent;

    public void onViewClicked(View view) {
        mIntent = new Intent();
        switch (view.getId()) {
            case R.id.ll_transfertype:
                //异动类型
                mIntent = new Intent(TransferApplyTypeActivity.this, TransferCheckActivity.class);
                mIntent.putExtra("type", "0");
                mIntent.putExtra("checkId", checkId);
                startActivityForResult(mIntent, 1001);
                break;
            case R.id.ll_reason:
                //异动原因
                mIntent = new Intent(TransferApplyTypeActivity.this, TransferApplyMoreListActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("reasonsForChangeList",(Serializable) reasonsForChangeList);
                mIntent.putExtras(bundle);
                mIntent.putExtra("title","异动原因");
                startActivityForResult(mIntent, 1002);
                break;
            case R.id.ll_hr:
                //招募人
                mIntent = new Intent(TransferApplyTypeActivity.this, TransferApplySearchActivity.class);
                mIntent.putExtra("type", "0");
                startActivityForResult(mIntent, 1003);
                break;
            case R.id.llHrQuDao:
                //招募渠道
                mIntent = new Intent(TransferApplyTypeActivity.this, TransferApplyMoreListActivity.class);
                Bundle bundle2 = new Bundle();
                bundle2.putSerializable("reasonsForChangeList",(Serializable) recruitmentChannelsList);
                mIntent.putExtras(bundle2);
                mIntent.putExtra("title","招募渠道");
                startActivityForResult(mIntent, 1004);
                break;
            case R.id.bt_next:
                checkDatas();
                break;
            case R.id.back_btn:
                finish();
                break;
        }
    }

    private void checkDatas() {
        if (TextUtils.isEmpty(binding.tvTransfertype.getText().toString())) {
            CustomToast.showToast(TransferApplyTypeActivity.this, "请选择异动类型", 1500);
        } else if (TextUtils.isEmpty(binding.tvReason.getText().toString())) {
            CustomToast.showToast(TransferApplyTypeActivity.this, "请选择异动原因", 1500);
        }
//        else if(llHrall.getVisibility() ==View.VISIBLE && TextUtils.isEmpty(tvHr.getText().toString())){
//            CustomToast.showToast(TransferApplyTypeActivity.this,"请选择招募人",1500);
//        }
        else if ("0".equals(userLevel) && !"diaogang".equals(typeCode)) {
            CustomToast.showToast(TransferApplyTypeActivity.this, "非地产人员只能选择调岗", 1500);
        } else if (!"0".equals(userLevel) && "diaogang".equals(typeCode)) {
            CustomToast.showToast(TransferApplyTypeActivity.this, "地产人员不可以调岗", 1500);
        } else if ("cizhi".equals(typeCode)||"citui".equals(typeCode)||"shixiqilizhi".equals(typeCode)){
            pushData();
        }else {
            mIntent = new Intent(TransferApplyTypeActivity.this, TransferApplyHierarchyActivity.class);
            mIntent.putExtra("bean", transferBean);
            mIntent.putExtra("lower", lower);
            startActivity(mIntent);
        }
    }

    private int checkId = -1;
    private int checkIdReson = -1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1001) {
                binding.tvTransfertype.setText(data.getStringExtra("name"));
                binding.tvReason.setText("");
                userLevel = data.getStringExtra("userLevel");//原有职务等级
                lower = data.getBooleanExtra("lower", false);
                typeCode = data.getStringExtra("code");//异动类型code
                checkId = data.getIntExtra("checkId", -1);
                Bundle bundle = data.getExtras();
                reasonsForChangeList = (ArrayList<Map<String,Object>>)bundle.getSerializable("reasonsForChangeList");
                recruitmentChannelsList = (ArrayList<Map<String,Object>>)bundle.getSerializable("recruitChannelList");
                if ("cizhi".equals(typeCode)||"citui".equals(typeCode)||"shixiqilizhi".equals(typeCode)){
                    binding.btNext.setText("提交");
                }else{
                    binding.btNext.setText("下一步");
                }
                if ("新入司".equals(data.getStringExtra("name"))) {
                    binding.llHrall.setVisibility(View.VISIBLE);
                } else {
                    binding.llHrall.setVisibility(View.GONE);
                    transferBean.setRecruitPin("");
                }
                transferBean.setUserbdTypeName(data.getStringExtra("name"));
                transferBean.setUserbdTypeCode(data.getStringExtra("code"));

            } else if (requestCode == 1002) {
                binding.tvReason.setText(data.getStringExtra("reason"));
                transferBean.setRemark(data.getStringExtra("reason"));
                //checkIdReson = data.getIntExtra("checkId", -1);
                //userLevel = data.getStringExtra("userLevel");//原有职务等级
            } else if (requestCode == 1003) {
                binding.tvHr.setText(data.getStringExtra("userName"));
                transferBean.setRecruitPin(data.getStringExtra("pin"));
            } else if (requestCode == 1004) {
                binding.tvHrQuDao.setText(data.getStringExtra("reason"));
                transferBean.setHrQuDao(data.getStringExtra("reason"));
            }
        }
    }

    private void formatStr(TextView view, String word) {
        String tmp = "<font color=\"red\">" + word + "</font>";
        String str = view.getText().toString().replace(word, tmp);
        //Html.fromHtml(str)
        view.setText(Html.fromHtml(str));
    }

    @Subscriber
    public void onEvent(TransferApplySuccessEvent event) {
        if (event.getResult() == 0) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 提交异动申请
     */
    private void pushData() {
        progressDialog.show();
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("userbdTypeName",binding.tvTransfertype.getText());
      jsonObject.put("userbdTypeCode",typeCode);
      jsonObject.put("remark", binding.tvReason.getText());
        OkHttpUtils
                .postString()
                .url(ApiConfig.TRANSFER_CONFIRM)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(TransferApplyTypeActivity.this, response, null)) {
                            mIntent = new Intent(TransferApplyTypeActivity.this, CommitSuccessActivity.class);
                            startActivity(mIntent);
                        } else {
                            String message = response.get("message").toString();
                            CustomToast.showToast(TransferApplyTypeActivity.this, message, 1500);
                        }
                    }
                });
    }
}
